package org.cllib.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class PackageModifier {
	private final static String EXTENSION_SEPARATOR = ".";
	private final static String EXTENSION_JAVA_SOURCE_CODE = "java";
	private final static String PACKAGE_SEPARATOR = ".";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		String encoding = System.getProperty("source.encoding" , System.getProperty("file.encoding"));
		String packageName = System.getProperty("package.name" , "");
		// TODO Auto-generated method stub
		for (int i = 0; i < args.length; i++) {
			File f = new File(args[i]);
			if (f.isDirectory()) {
				renameJavaSourceFilePackageDeclaration(f , packageName , encoding);
			}
		}
	}
	
	private static void renameJavaSourceFilePackageDeclaration(File dir ,String packageName , String encoding) throws Exception{
		if(dir.isDirectory()){
			File[] sourceFiles = dir.listFiles(new FileFilter(){

				public boolean accept(File pathname) {
					// TODO Auto-generated method stub
					String name = pathname.getName();
					int di = name.indexOf(EXTENSION_SEPARATOR);
					if(di >= 0){
						String suffix = name.substring(di + 1);
						if(suffix.equalsIgnoreCase(EXTENSION_JAVA_SOURCE_CODE)){
							return true;
						}
					}
					return false;
				}
				
			});
			
			for (int i = 0; i < sourceFiles.length; i++) {
				File f = sourceFiles[i];
				byte[] buffer = new byte[512 * 1024];
				int lengthRead = -1;
				FileInputStream fis = new FileInputStream(f);
				
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while((lengthRead = fis.read(buffer, 0, buffer.length)) != -1){
					baos.write(buffer , 0 , lengthRead);
				}
				
				baos.flush();
				byte[] data = baos.toByteArray();
				String fileContent = new String(data , 0 , data.length , encoding);
				
				if(!packageName.endsWith(PACKAGE_SEPARATOR)){
					packageName += PACKAGE_SEPARATOR;
				}
				
				fileContent = fileContent.replaceFirst("package .*;", packageName + dir.getName() + ";");

				FileOutputStream fos = new FileOutputStream(f);
				data = fileContent.getBytes(encoding);
				
				fos.write(data, 0, data.length);
				fos.flush();
				fos.close();
			}
		}
	}

}
